package com.ly.cyclictest.test02;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    /**
     *
     *多线程
     */
    static boolean flag = false;

    private final static CyclicBarrier cyclicBarrier = new CyclicBarrier(10,new Runnable(){

        @Override
        public void run() {
            if (flag){
                System.out.println("回");
            }else {
                System.out.println("开始执行");
                flag=true;
            }
        }
    });

    public static void main(String[] args) {
        for (int i = 0 ; i<10 ; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName()+"集合");
                        cyclicBarrier.await();
                        Thread.sleep(Math.abs(new Random().nextInt()%10000));
                        System.out.println(Thread.currentThread().getName()+"执行");
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
